package com.jason.schedulemigrationtest.common;


import com.jason.schedulemigrationtest.service.DataMigrationService;
import com.jason.schedulemigrationtest.service.MigrationArchiveLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

@Slf4j
@Component
public class DataMigrationScheduler {

    @Value("${data.migration.enabled:true}")
    private boolean enabled;    // 是否开启迁移任务
    @Value("${data.migration.days-ago:120}")
    private int intervalDays;   // 迁移数据的时间范围，单位天
    @Value("${data.migration.page-size:1000}")
    private int pageSize;       // 每页迁移数据的数量

    @Resource
    private DataMigrationService dataMigrationService;  // 数据迁移服务
    @Resource
    private MigrationArchiveLogService migrationArchiveLogService;  // 迁移日志服务

    @Scheduled(cron ="${data.migration.cron:0 0 3 * * ?}", zone = "Asia/Shanghai")   // 每天凌晨3点执行一次
    public void dataMigrationTask() {
        if(!enabled){
            return;
        }

        log.info("迁移 express_order 表定时任务执行中,pageSize:"+ pageSize +"...");
        // 计算迁移数据的截止日期
        String cutoff = LocalDate.now(ZoneId.of("Asia/Shanghai"))
                .minusDays(intervalDays)          // intervalDays 例如 90
                .format(DateTimeFormatter.ISO_LOCAL_DATE);
        log.info("开始迁移 "+cutoff+" 之前的数据");

        int total= 0;
        List<Long> pageOrderIds = null;
        Long lastId = null;
        do {
            // 查询需要迁移的数据订单号集合
            pageOrderIds = dataMigrationService.queryIdsByCutoff(cutoff, lastId, pageSize);
            if (pageOrderIds.isEmpty()) {
                break;
            }

            Long startOrderId = pageOrderIds.get(0);
            Long endOrderId = pageOrderIds.get(pageOrderIds.size() - 1);
            int idsSize = pageOrderIds.size();
            log.info("共查询到" + idsSize + "条数据 -> start: " + startOrderId+" end: " + endOrderId);
            lastId = pageOrderIds.get(idsSize-1); // 下一页的起始订单号

            // 生成迁移日志服务的批次ID
            String batchId = UUID.randomUUID().toString();
            String msg = "";
            int counts = 0;
            try {
                // 调用数据迁移服务进行迁移
                counts = dataMigrationService.migrateDataByIds(pageOrderIds);
                total += counts;
            } catch (Exception e) {
                msg = e.getMessage();
                log.error("批次 {} 迁移失败: {}", batchId, msg, e);
            }
            // 记录迁移日志
            migrationArchiveLogService.recordMigration(batchId, startOrderId, endOrderId, counts, msg);

        } while (pageOrderIds.size() == pageSize);
        log.info("迁移结束,共迁移完成 "+ total +" 条数据");
    }

}